package service

import (
	"errors"

	"publish-manage/internal/model"
	"publish-manage/pkg/database"
	"publish-manage/pkg/domain"
	"publish-manage/pkg/util"
)

var ApplicationService = new(applicationService)

type applicationService struct{}

func (_ *applicationService) Add(instance *model.Application) (bool, error) {
	if instance.Name == "" {
		return false, errors.New("应用名称不能为空")
	}

	if c, err := database.DB.Count(&model.Application{Name: instance.Name}); err != nil {
		return false, err
	} else if c > 0 {
		return true, nil
	}

	instance.Id = util.GenerateDatabaseID()
	if _, err := database.DB.Insert(instance); err != nil {
		return false, err
	}

	return false, nil
}

func (_ *applicationService) Update(instance *model.Application) error {
	if instance.Id == "" {
		return errors.New("id不能为空")
	}

	_, err := database.DB.ID(instance.Id).Update(&model.Application{
		Name: instance.Name,
	})

	return err
}

func (_ *applicationService) Delete(id string) error {
	if id == "" {
		return errors.New("id不能为空")
	}

	session := database.DB.NewSession()
	defer session.Close()
	session.Begin()

	if _, err := session.Delete(&model.Application{Id: id}); err != nil {
		return err
	}
	if _, err := session.Delete(&model.AppPackage{AppId: id}); err != nil {
		return err
	}
	if _, err := session.Delete(&model.PackageVersion{AppId: id}); err != nil {
		return err
	}
	return session.Commit()
}

func (_ *applicationService) Get(instance *model.Application) (*model.Application, error) {
	if instance.Id == "" {
		return nil, errors.New("id不能为空")
	}

	if exist, err := database.DB.Get(instance); err != nil {
		return nil, err
	} else if !exist {
		return nil, nil
	}
	return instance, nil
}

func (_ *applicationService) List(condition *model.Application, offset, limit int, orderBy string) (pageInfo *domain.Paginate, err error) {
	// 处理不允许查询的字段

	// 处理sql
	session := database.DB.NewSession()
	if limit > -1 && offset > -1 {
		session.Limit(limit, offset)
	}

	if orderBy != "" {
		session.OrderBy(orderBy)
	}
	session.Desc("create_time")

	// 模糊查找
	if condition.Name != "" {
		session.Where("name like ?", condition.Name+"%")
		condition.Name = ""
	}

	var list []*model.Application
	total, err := session.FindAndCount(&list, condition)
	if err != nil {
		return nil, err
	}

	return &domain.Paginate{
		Total:  int(total),
		Offset: offset,
		Limit:  limit,
		Items:  list,
	}, nil
}
